<?php
/**
 * Created by PhpStorm.
 * User: dungnt
 * Date: 12/3/14
 * Time: 10:05 PM
 */

namespace App\Services;


class BaseService
{
    private $redis;

    public function saveItem($className, $arrParams, $options = array())
    {
        $class = !empty($arrParams['id']) ? $className::find($arrParams['id']) : new $className();
        foreach ($arrParams as $key => $value) {
            if ($key != 'id') {
                $class->{$key} = $value;
            }
        }
        $class->save();
        if (isset($options['return']) && $options['return'] == 'class')
            return $class;
        else
            return $class->id;

    }

//    public function attachVote($data)
//    {
//        if (is_numeric($data['id'])) {
//            if (!is_null($class = $data['Class']::find($data['id']))) {
//                try {
//                    $class->votes()->detach($data['user_id']);
//                    if ($data['remove'] == false)
//                        $class->votes()->attach($data['user_id']);
//                    $class->{$data['field']} = $class->votes()->count();
//                    $class->save();
//                    return $class->{$data['field']};
//                } catch (Exception $ex) {
//                    return false;
//                }
//            }
//        }
//        return false;
//    }

    public function attach($data)
    {
        if (is_numeric($data['id'])) {
            if (!is_null($class = $data['Class']::find($data['id']))) {
                try {
                    $class->$data['function']()->detach($data['user_id']);
                    if ($data['remove'] == false)
                        $class->$data['function']()->attach($data['user_id']);
                    $class->{$data['field']} = $class->$data['function']()->count();
                    $class->save();
                    return $class->{$data['field']};
                } catch (Exception $ex) {
                    return false;
                }
            }
        }
        return false;
    }


    public function redis()
    {
        if (empty($this->redis))
            $this->redis = \Redis::connection();
        return $this->redis;
    }
} 